package logic

import (
	"yuanxin-admin/internal/model"
	"yuanxin-admin/internal/repository"
	"yuanxin-admin/internal/service"

	"gitee.com/botaoshow/yuanxin/web/common/database"
	"gitee.com/botaoshow/yuanxin/web/utils/strs"
	"github.com/gin-gonic/gin"
)

func NewSysRoleService() service.ISysRoleService {
	return &SysRoleServiceImpl{}
}

type SysRoleServiceImpl struct {
}

func (s SysRoleServiceImpl) AddUrl(c *gin.Context, roleIds []string, urlIds []string) (bool, error) {

	db := repository.Use(database.Db)

	err := db.Transaction(func(tx *repository.Query) error {
		var list []*model.SysRoleURL
		for _, urlId := range urlIds {
			for _, roleId := range roleIds {
				o := model.SysRoleURL{
					ID:     strs.GetUUIDWithoutDashUpper(),
					RoleID: roleId,
					URLID:  urlId,
				}
				list = append(list, &o)
			}
		}
		for _, item := range list {
			_, err := tx.SysRoleURL.WithContext(c).
				Where(tx.SysRoleURL.URLID.Eq(item.URLID)).
				Where(tx.SysRoleURL.RoleID.Eq(item.RoleID)).Delete()
			if err != nil {
				return err
			}
		}
		err := tx.SysRoleURL.WithContext(c).CreateInBatches(list, 100)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return false, err
	}
	return true, nil
}

func (s SysRoleServiceImpl) RemoveUrl(c *gin.Context, roleIds []string, urlIds []string) (bool, error) {
	db := repository.Use(database.Db)

	err := db.Transaction(func(tx *repository.Query) error {
		var list []*model.SysRoleURL
		for _, urlId := range urlIds {
			for _, roleId := range roleIds {
				o := model.SysRoleURL{
					ID:     strs.GetUUIDWithoutDashUpper(),
					RoleID: roleId,
					URLID:  urlId,
				}
				list = append(list, &o)
			}
		}
		for _, item := range list {
			_, err := tx.SysRoleURL.WithContext(c).
				Where(tx.SysRoleURL.URLID.Eq(item.URLID)).
				Where(tx.SysRoleURL.RoleID.Eq(item.RoleID)).Delete()
			if err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		return false, err
	}
	return true, nil
}
